<?php
YII::import('application.extensions.YiiMailer.YiiMailer');
class PaymentController extends Controller
{
    private $test_customer_list = array(
        'aurora101@gmail.com',  //72609
        'ruishujiao@126.com',   //86658
        'ruishujiao@gmail.com', //109251
        'ruishujiao@yahoo.com', //109252
    );
	
	public function accessRules()
	{
		return array(
				array('allow', // allow admin user to perform 'admin' and 'delete' actions
						'actions'=>array('index','buybidpack','buyauctions','authorizenet','paypal','testpayment','zeroPayment','braintree'),
						'users'=>array('@'),
				),
				array('deny',  // deny all users
						'users'=>array('*'),
				),
		);
	}
	
	public function init(){
        parent::init();
		$this->layout = 'splash';
//         if(Yii::app()->params['server_environment']=='live'){
             $this->https();
//         }
	}
	
	public function actionBuyBidPack(){
		$paymentData = Parameters::post('CustomerOrderBillingInfo');
		//save customer
		$CustomerModel = new Customer();
		$CustomerData = $CustomerModel->find("t.id =".Yii::app()->user->id);
		$customerInfo	= $CustomerData->attributes;
		$customerInfo['paymentsource'] = trim($paymentData->paymentsource)!=''?$paymentData->paymentsource:'';
		$customerId		= Yii::app()->user->id;
		
		$paymentInfo	= new PaymentInfo(array(
						new PaymentCustomer(),
		));

		switch ($paymentData->billing_payby){
			case AuthorizeNet::API_NAME:
				$paymentInfo->setPaymentData(new PaymentBilling());
				$paymentInfo->setPaymentData(new PaymentCreditCard());
				//billing info ;
				$paymentInfo->billingInfo->billingId	=   $paymentData->billing_id;
				$paymentInfo->billingInfo->customerId	=	$customerId;
				$paymentInfo->billingInfo->firstName	=	$paymentData->billing_first_name;
				$paymentInfo->billingInfo->lastName		=	$paymentData->billing_last_name;
				$paymentInfo->billingInfo->address1		=	$paymentData->billing_address1;
				$paymentInfo->billingInfo->address2		=	$paymentData->billing_address1;
				$paymentInfo->billingInfo->city			=	$paymentData->billing_city;
				$paymentInfo->billingInfo->state		=	$paymentData->billing_state;
				$paymentInfo->billingInfo->country		=	$paymentData->billing_country;
				$paymentInfo->billingInfo->zip			=	$paymentData->billing_zip;
				$paymentInfo->billingInfo->email		=	$paymentData->billing_email;
				$paymentInfo->billingInfo->phone		=	$paymentData->billing_phone;
				
				$paymentInfo->creditCardInfo->cardNumber 	= $paymentData->credit_card_num;
				$paymentInfo->creditCardInfo->cardCode 		= $paymentData->credit_card_cvv;
				$paymentInfo->creditCardInfo->cardExpDate 	= mktime(0,0,0,$paymentData->credit_card_exp_month,1,$paymentData->credit_card_exp_year);
				break;
			case PayPal::API_NAME:
				break;
			case Braintree::API_NAME:
				$paymentInfo->setPaymentData(new PaymentBilling());
				$paymentInfo->setPaymentData(new PaymentCreditCard());
		
				//billing info ;
				$paymentInfo->billingInfo->billingId	=   $paymentData->billing_id;
				$paymentInfo->billingInfo->customerId	=	$customerId;
				$paymentInfo->billingInfo->firstName	=	$paymentData->billing_first_name;
				$paymentInfo->billingInfo->lastName		=	$paymentData->billing_last_name;
				$paymentInfo->billingInfo->address1		=	$paymentData->billing_address1;
				$paymentInfo->billingInfo->address2		=	$paymentData->billing_address1;
				$paymentInfo->billingInfo->city			=	$paymentData->billing_city;
				$paymentInfo->billingInfo->state		=	$paymentData->billing_state;
				$paymentInfo->billingInfo->country		=	$paymentData->billing_country;
				$paymentInfo->billingInfo->zip			=	$paymentData->billing_zip;
				$paymentInfo->billingInfo->email		=	$paymentData->billing_email;
				$paymentInfo->billingInfo->phone		=	$paymentData->billing_phone;
		
				$paymentInfo->creditCardInfo->cardNumber 	= $paymentData->credit_card_num;
				$paymentInfo->creditCardInfo->cardCode 		= $paymentData->credit_card_cvv;
				$paymentInfo->creditCardInfo->cardExpDate 	= mktime(0,0,0,$paymentData->credit_card_exp_month,1,$paymentData->credit_card_exp_year);
				break;	
		}
		
		$paymentInfo->setPaymentCode(Payment::createPaymentCode(array('customerId' => $customerId,'objId'=>$paymentData->bidPackId)));
		//
		$paymentInfo->customer->setCustomerInfo($customerInfo);
		//coupon code valid
		
		$tempData = $paymentData->toArray();
		if(!empty($tempData['coupon_code'])){
			$paymentInfo->setPaymentData(new PaymentCouponCode());
			$paymentInfo->bidPack->setCouponCode($paymentData->coupon_code);


            $couponCodeValidService = new CouponCodeVerificationService();
            $return = $couponCodeValidService->setCouponCode($paymentData->coupon_code)->setCouponCodeData()->verification();

            if(!$return){
                Yii::app()->session['_responder_mark'] = 'mark';
                $this->redirect('buybid/index');
            }
            unset(Yii::app()->session['_responder_mark']);

// 			$return = $paymentInfo->couponCode->setCouponCode($paymentData->coupon_code)->setCouponCodeData()->verification();
// 			if($return){
// 				$paymentInfo->couponCode->lessCouponCode();
// 				$paymentInfo->totalPrice = $paymentInfo->couponCode->setPrice($paymentInfo->bidPack->bidPackPrice)->useCouponCode();
// 				$paymentInfo->bidPack->bidPackPrice = $paymentInfo->totalPrice;
// 			}

		}

		else{

			$paymentInfo->setPaymentData(new PaymentBidPack());

			$paymentInfo->bidPack->getBidPackInfo($paymentData->bidPackId);
		}
		$paymentInfo->totalPrice = floatval($paymentInfo->bidPack->bidPackPrice);

		if($paymentInfo->vaild()){
			$paymentInfo->saveCache();
            if($paymentInfo->totalPrice <= 0){
                $url = Yii::app()->createUrl('payment/zeroPayment',array('paymentCode' => $paymentInfo->getPaymentCode()));
                $this->redirect($url);
                
            }

			//test order
			//modify lh 2015-03-09
			
            //$this->redirect(Yii::app()->createUrl('payment/testpayment',array('paymentCode' => $paymentInfo->getPaymentCode() )));
			
			if(in_array($paymentInfo->customer->email,$this->test_customer_list)){
				//send mail

				$sendGrid = Yii::app()->sendGrid;

                $sendGrid->mail()->addTo('guo.hao@ebiz-interactive.com');
				$sendGrid->mail()->addTo('mason@infinitenine.com');
                $sendGrid->mail()->addTo('dbebiztest@gmail.com');

				$sendGrid->mail()->setSubject('Customer '.$paymentInfo->customer->email.' buy to'.time().' Date'.date('Y-m-d H:i:s'));
				$sendGrid->mail()->setHtml('Customer '.$paymentInfo->customer->email.' buy to'.time().' Date'.date('Y-m-d H:i:s').' ip :'.Yii::app()->tools->getIp());
				$sendGrid->send();
				
				$this->redirect(Yii::app()->createUrl('payment/testpayment',array('paymentCode' => $paymentInfo->getPaymentCode() )));
			}
			switch ($paymentData->billing_payby){
				case AuthorizeNet::API_NAME:
					$this->redirect(Yii::app()->createUrl('payment/authorizeNet',array('paymentCode' => $paymentInfo->getPaymentCode() )));
					break;
				case PayPal::API_NAME:
					$this->redirect(Yii::app()->createUrl('payment/paypal',array('paymentCode' => $paymentInfo->getPaymentCode()) ));
					break;
				case Braintree::API_NAME:
					$this->redirect(Yii::app()->createUrl('payment/braintree',array('paymentCode' => $paymentInfo->getPaymentCode()) ));
					break;
			}
			
		}else{

			Yii::app()->session['payment_error'] = 'Please try using PayPal or call your Bank/Credit Card Company and ask them to approve transactions to eGunner Penny Auctions, LLC. If you have further questions, please contact eGunner Penny Auctions support at: https://egunner.desk.com!';
			$model = new PaymentLog();
			$model->type = ($paymentData->billing_payby == 'AuthorizeNet')?2:1;
			$model->request = $paymentInfo->getPaymentCode();
			$model->customer_id = Yii::app()->user->id;
			$model->created = time();
			$model->response = json_encode($paymentInfo->errorMessage());
			$model->save();
			$this->redirect(Yii::app()->baseUrl);
// 			Yii::app()->request->getUrlReferrer();
// 			var_dump($paymentInfo->errorMessage());
		}
		
	}
	
	public function actionBuyAuctions(){
		$paymentData = Parameters::post('CustomerOrderBillingInfo');
		//save customer
		$CustomerModel = new Customer();
		$CustomerData = $CustomerModel->find("t.id =".Yii::app()->user->id);
		$customerInfo	= $CustomerData->attributes;
		$customerInfo['paymentsource'] = '';

		$customerId		= Yii::app()->user->id;
		$paymentCode = $paymentData->paymentCode;
		$paymentInfo = new PaymentInfo();
		$paymentInfo->setPaymentCode($paymentCode);
		$paymentInfo->getCache();
		//order vaild
		if(!$paymentInfo->vaild()){
			
			$orderError = new OrderErrorLog();
			$orderError->customer_id 	= $customerId;
			$orderError->auction_id 	= $paymentInfo->auction->id;
			$orderError->created 		= time();
			$orderError->post_data 		= json_encode($paymentInfo->toArray());
			$orderError->error_message  = json_encode($paymentInfo->errorMessage());
			$orderError->url			= Yii::app()->request->getUrl();
			$orderError->save(false);

			$this->redirect(Yii::app()->createUrl('.'));
		}

		$paymentInfo->setPaymentData(new PaymentCustomer());

		switch ($paymentData->billing_payby){
			case AuthorizeNet::API_NAME:
				$paymentInfo->setPaymentData(new PaymentBilling());
				$paymentInfo->setPaymentData(new PaymentCreditCard());
		
				//billing info ;
				$paymentInfo->billingInfo->billingId	=   $paymentData->billing_id;
				$paymentInfo->billingInfo->customerId	=	$customerId;
				$paymentInfo->billingInfo->firstName	=	$paymentData->billing_first_name;
				$paymentInfo->billingInfo->lastName		=	$paymentData->billing_last_name;
				$paymentInfo->billingInfo->address1		=	$paymentData->billing_address1;
				$paymentInfo->billingInfo->address2		=	$paymentData->billing_address1;
				$paymentInfo->billingInfo->city			=	$paymentData->billing_city;
				$paymentInfo->billingInfo->state		=	$paymentData->billing_state;
				$paymentInfo->billingInfo->country		=	$paymentData->billing_country;
				$paymentInfo->billingInfo->zip			=	$paymentData->billing_zip;
				$paymentInfo->billingInfo->email		=	$paymentData->billing_email;
				$paymentInfo->billingInfo->phone		=	$paymentData->billing_phone;
				$paymentInfo->giftCard=$paymentData->giftcard_check;
		
				$paymentInfo->creditCardInfo->cardNumber 	= $paymentData->credit_card_num;
				$paymentInfo->creditCardInfo->cardCode 		= $paymentData->credit_card_cvv;
				$paymentInfo->creditCardInfo->cardExpDate 	= mktime(0,0,0,$paymentData->credit_card_exp_month,1,$paymentData->credit_card_exp_year);
				break;
			case PayPal::API_NAME:
				break;
			case Braintree::API_NAME:
				$paymentInfo->setPaymentData(new PaymentBilling());
				$paymentInfo->setPaymentData(new PaymentCreditCard());
		
				//billing info ;
				$paymentInfo->billingInfo->billingId	=   $paymentData->billing_id;
				$paymentInfo->billingInfo->customerId	=	$customerId;
				$paymentInfo->billingInfo->firstName	=	$paymentData->billing_first_name;
				$paymentInfo->billingInfo->lastName		=	$paymentData->billing_last_name;
				$paymentInfo->billingInfo->address1		=	$paymentData->billing_address1;
				$paymentInfo->billingInfo->address2		=	$paymentData->billing_address1;
				$paymentInfo->billingInfo->city			=	$paymentData->billing_city;
				$paymentInfo->billingInfo->state		=	$paymentData->billing_state;
				$paymentInfo->billingInfo->country		=	$paymentData->billing_country;
				$paymentInfo->billingInfo->zip			=	$paymentData->billing_zip;
				$paymentInfo->billingInfo->email		=	$paymentData->billing_email;
				$paymentInfo->billingInfo->phone		=	$paymentData->billing_phone;
		
				$paymentInfo->creditCardInfo->cardNumber 	= $paymentData->credit_card_num;
				$paymentInfo->creditCardInfo->cardCode 		= $paymentData->credit_card_cvv;
				$paymentInfo->creditCardInfo->cardExpDate 	= mktime(0,0,0,$paymentData->credit_card_exp_month,1,$paymentData->credit_card_exp_year);
				break;
		}
		$paymentInfo->customer->setCustomerInfo($customerInfo);
		if(is_object($paymentInfo->orderInfo)){
			$paymentInfo->totalPrice = ($paymentInfo->orderInfo->total_price)-($paymentInfo->orderInfo->count_price);
		}elseif(is_object($paymentInfo->buyItNow)){
			$paymentInfo->totalPrice = $paymentInfo->buyItNow->total_price;
		}

		$paymentInfo->giftCard=$paymentData->giftcard_check;

		if($paymentInfo->vaild()){
			$paymentInfo->saveCache();

            $total_price = floatval($paymentInfo->totalPrice);

 			if ($total_price <= 0){
 				$this->redirect(Yii::app()->createUrl('payment/zeroPayment',array('paymentCode' => $paymentInfo->getPaymentCode()) ));
 			}
			//test order
 			//$this->redirect(Yii::app()->createUrl('payment/testpayment',array('paymentCode' => $paymentInfo->getPaymentCode() )));
			if(in_array($paymentInfo->customer->email,$this->test_customer_list)){
				//send mail
				$sendGrid = Yii::app()->sendGrid;

				$sendGrid->mail()->addTo('guo.hao@ebiz-interactive.com');
				$sendGrid->mail()->addTo('mason@infinitenine.com');
				$sendGrid->mail()->addTo('dbebiztest@gmail.com');

				$sendGrid->mail()->setSubject('Customer '.$paymentInfo->customer->email.' buy to'.time().' Date'.date('Y-m-d H:i:s'));
				$sendGrid->mail()->setHtml('Customer '.$paymentInfo->customer->email.' buy to'.time().' Date'.date('Y-m-d H:i:s').' ip :'.Yii::app()->tools->getIp());
				$sendGrid->send();
			
				$this->redirect(Yii::app()->createUrl('payment/testpayment',array('paymentCode' => $paymentInfo->getPaymentCode() )));
			}
			
			switch ($paymentData->billing_payby){
				case AuthorizeNet::API_NAME:
					$this->redirect(Yii::app()->createUrl('payment/authorizeNet',array('paymentCode' => $paymentInfo->getPaymentCode() )));
					break;
				case PayPal::API_NAME:
					$this->redirect(Yii::app()->createUrl('payment/paypal',array('paymentCode' => $paymentInfo->getPaymentCode()) ));
					break;
				case ZeroPayment::API_NAME:
					$this->redirect(Yii::app()->createUrl('payment/zeropayment',array('paymentCode' => $paymentInfo->getPaymentCode()) ));
					break;
				case Braintree::API_NAME:
					$this->redirect(Yii::app()->createUrl('payment/braintree',array('paymentCode' => $paymentInfo->getPaymentCode()) ));
					break;
			}
		}else{
			Yii::app()->session['payment_error'] =  'Please try using PayPal or call your Bank/Credit Card Company and ask them to approve transactions to eGunner Penny Auctions, LLC. If you have further questions, please contact eGunner Penny Auctions support at: https://egunner.desk.com!';
			$model = new PaymentLog();
			$model->type = ($paymentData->billing_payby == 'AuthorizeNet')?2:1;
			$model->request = $paymentInfo->getPaymentCode();
			$model->customer_id = Yii::app()->user->id;
			$model->created = time();
			$model->response = json_encode($paymentInfo->errorMessage());
			$model->save();
			$this->redirect(Yii::app()->baseUrl);
		}
	}
	
	public function actionAuthorizeNet(){
	    $referrer=Yii::app()->getRequest()->urlReferrer;
	    $returnUrl="";
		$paymentCode = Parameters::get()->paymentCode;

		$paymentInfo = new PaymentInfo(); 
		$paymentInfo->setPaymentCode($paymentCode)->getCache();
		//order vaild
		if(!$paymentInfo->vaild()){
			
			$orderError = new OrderErrorLog();
			$orderError->customer_id 	= $paymentInfo->customer->id;;
			$orderError->auction_id 	= $paymentInfo->auction->id;
			$orderError->created 		= time();
			$orderError->post_data 		= json_encode($paymentInfo->toArray());
			$orderError->error_message  = json_encode($paymentInfo->errorMessage());
			$orderError->url			= Yii::app()->request->getUrl();
			
			$orderError->save(false);

			$this->redirect(Yii::app()->createUrl('.'));
		}
		$api = new AuthorizeNet($paymentInfo);
		$api->apiRequest();
		$response = $api->apiResponse();

		if (is_object($paymentInfo->orderInfo)||is_object($paymentInfo->buyItNow)){
		    $returnUrl="checkout/order";
		}

		if ($api->apiPaymentVaild()){
			if(is_object($paymentInfo->bidPack)){
				$buyBid = new PaymentBuyBid($paymentInfo);
				$buyBid->setProcessInfo(array('paymentType' => 2));
				$buyBid->save();
			}
			if(is_object($paymentInfo->orderInfo)||is_object($paymentInfo->buyItNow)){
				if(is_object($paymentInfo->buyItNow)){
					if($paymentInfo->giftCard==1){
						$total_price_old = $paymentInfo->buyItNow->total_price;
						$old_tax_fee = $paymentInfo->buyItNow->tax_fee;
						$total_price = bcsub($total_price_old,$old_tax_fee,2);
						$paymentInfo->buyItNow->tax_fee = 0;
						$paymentInfo->buyItNow->total_price = $total_price;
						$paymentInfo->buyItNow->_orderAr->total_price = $total_price;
						$paymentInfo->buyItNow->_orderAr->tax_fee = 0;
					}
				}
				$buyAuction = new PaymentBuyAuction($paymentInfo);
				$buyAuction->setProcessInfo(array('paymentType' => 2));
				$buyAuction->save()->redirect();
			}
		}else{
			Yii::app()->session['paymentError'] = array(
				'paymentCode'	=>	$paymentCode,
				'paymentType'	=>	AuthorizeNet::API_NAME,
			);
			$couponCodeValidService = new CouponCodeVerificationService();
			$couponCodeValidService->setCouponCode($paymentInfo->coupon_code)->addCouponCode();
		
			//$api->paymentLog(json_encode($response));
			$model = new PaymentLog();
			$model->type = 2;
			$model->request = $paymentCode;
			$model->customer_id = Yii::app()->user->id;
			$model->created = time();
			$model->response = json_encode(json_encode($response));
			$model->save();
				
			Yii::app()->user->setFlash('payment failed', 'Please try calling your Bank/Credit Card Company and ask them to approve transactions to egunner.com, LLC. If you have further questions, please contact us support at: <a href="https://egunner.desk.com" target="_blank">https://egunner.desk.com!</a>');
			if (!empty($returnUrl)){
    			$this->redirect(Yii::app()->createUrl($returnUrl,array("paymentcode"=>$paymentCode)));
			}else{
			    $this->redirect($referrer);
			}
		}
		$this->redirect(Yii::app()->baseUrl.'/myaccount/bidcredithistory');
	}
	
	public function actionPaypal(){
		$paymentCode = Parameters::get()->paymentCode;
		$token = Parameters::request()->token;
		
		$paymentInfo = new PaymentInfo();
		$paymentInfo->setPaymentCode($paymentCode)->getCache();

		//order vaild
		
		if(!$paymentInfo->vaild()){
			$orderError = new OrderErrorLog();
			$orderError->customer_id 	= $paymentInfo->customer->id;;
			$orderError->auction_id 	= $paymentInfo->auction->id;
			$orderError->created 		= time();
			$orderError->post_data 		= json_encode($paymentInfo->toArray());
			$orderError->error_message  = json_encode($paymentInfo->errorMessage());
			$orderError->url			= Yii::app()->request->getUrl();
				
			$orderError->save(false);
		
			$this->redirect(Yii::app()->createUrl('.'));
		}
		
		$payPal = new PayPal($paymentInfo);
		if(is_object($paymentInfo->bidPack)){
			$title = $paymentInfo->bidPack->bidPackTitle;
			$id = $paymentInfo->bidPack->bidPackId;
			$price = $paymentInfo->bidPack->bidPackPrice;
			$SHIPPINGAMT = 0;
		}elseif(is_object($paymentInfo->orderInfo)){
			$title = $paymentInfo->auction->title;
			$id = $paymentInfo->orderInfo->id;
			$price = $paymentInfo->orderInfo->price;
			$SHIPPINGAMT = ($paymentInfo->orderInfo->shipping_handling+$paymentInfo->orderInfo->shipping_fee);
		}elseif(is_object($paymentInfo->buyItNow)){
			$title = $paymentInfo->auction->title;
			$id = $paymentInfo->buyItNow->id;
			$price = $paymentInfo->buyItNow->price;
			$SHIPPINGAMT = ($paymentInfo->buyItNow->shipping_handling+$paymentInfo->buyItNow->shipping_fee);
		}
				
		if ($paymentInfo->existence(PaymentAmazonCard::NAME)) {
			$title = $paymentInfo->amazoncard->amazoncardInfo()->title;
		}
		
		$payPal->addItem(array(
				'title'	=>	$title,
				'id'	=>	$id,
				'price'	=>	($price > 0 )?$price:$SHIPPINGAMT,
				'SHIPPINGAMT'	=>	($price > 0 )?$SHIPPINGAMT:0,
		));
		if (!empty($token)){
			$payPal->setRequest(array('token' => $token));
			$payPal->apiRequest(PayPal::STEP_GETEXPRESSCHECKOUTDETAILS);
			
			if ($payPal->apiResponseVaild()){
				$couponcode = isset($paymentInfo->bidPack->couponCode)?$paymentInfo->bidPack->couponCode:null;
				if($couponcode){
					$cache = Yii::app()->cache;
					$codei = $cache->get($couponcode.'_'.$paymentInfo->customer->id);
					$cache->set($couponcode.'_'.$paymentInfo->customer->id,1800);
					$couponCodeValidService = new CouponCodeVerificationService();
					$return = $couponCodeValidService->setCouponCode($couponcode)->setCouponCodeData()->verification();
					if(!$return || $codei){
		                Yii::app()->session['_responder_mark'] = 'mark';
		                $this->redirect(Yii::app()->baseUrl.'/buybid/index');
		            }
		            unset(Yii::app()->session['_responder_mark']);
				}
				
				// paypal complent
				$payPal->apiRequest(PayPal::STEP_DOEXPRESSCHECKOUTPAYMENT);
				
				if ($payPal->apiPaymentVaild()){
					
					
					if(is_object($paymentInfo->bidPack)){
						$buyBid = new PaymentBuyBid($paymentInfo);
						$buyBid->setProcessInfo(array('paymentType' => 1));
						$buyBid->save()->redirect();
					}
					
					if(is_object($paymentInfo->orderInfo)||is_object($paymentInfo->buyItNow)){
						$buyAuction = new PaymentBuyAuction($paymentInfo);
						$buyAuction->setProcessInfo(array('paymentType' => 1));
						$buyAuction->save()->redirect();
					}
					
					$model = new PaymentLog();
					$model->type = 2;
					$model->request = $paymentCode;
					$model->customer_id = Yii::app()->user->id;
					$model->created = time();
					$model->response = json_encode(json_encode($response));
					$model->save();
					if($couponcode){
						$cache->delete($couponcode.'_'.$paymentInfo->customer->id);
					}
					Yii::app()->session['payment_error'] =  'Please try using PayPal or call your Bank/Credit Card Company and ask them to approve transactions to eGunner Penny Auctions, LLC. If you have further questions, please contact eGunner Penny Auctions support at: https://egunner.desk.com!';
					
					$this->redirect(Yii::app()->baseUrl.'/account');
				}else{
					if($couponcode){
						$cache->delete($couponcode.'_'.$paymentInfo->customer->id);
					}
					Yii::app()->session['payment_error'] = 'Please try using PayPal or call your Bank/Credit Card Company and ask them to approve transactions to eGunner Penny Auctions, LLC. If you have further questions, please contact eGunner Penny Auctions support at: https://egunner.desk.com!';
					
					$this->redirect(Yii::app()->baseUrl.'/account');
				}
			}else{
				if($couponcode){
					$cache->delete($couponcode.'_'.$paymentInfo->customer->id);
				}
				Yii::app()->session['payment_error'] =  'Please try using PayPal or call your Bank/Credit Card Company and ask them to approve transactions to eGunner Penny Auctions, LLC. If you have further questions, please contact eGunner Penny Auctions support at: https://egunner.desk.com!';
				$this->redirect(Yii::app()->baseUrl.'/account');
			}	
		}else{
			$payPal->paymentLog($payPal->getResponse());
			$payPal->apiRequest(PayPal::STEP_SETEXPRESSCHECKOUT);
		}
		Yii::app()->session['paymentError'] = array(
			'paymentCode'	=>	$paymentCode,
			'paymentType'	=>	PayPal::API_NAME,
		);
		$couponCodeValidService = new CouponCodeVerificationService();
		$couponCodeValidService->setCouponCode($paymentInfo->bidPack->couponCode)->addCouponCode();
		$this->redirect(Yii::app()->request->getUrlReferrer());
	}
	
	public function actionTestPayment(){		
		$paymentCode = Parameters::get()->paymentCode;

		$paymentInfo = new PaymentInfo();
		$paymentInfo->setPaymentCode($paymentCode)->getCache();
		$api = new TestPayment($paymentInfo);
		if($api->apiPaymentVaild()){
			if(is_object($paymentInfo->orderInfo)||is_object($paymentInfo->buyItNow)){
				if(is_object($paymentInfo->orderInfo)){
					$paymentInfo->orderInfo->merchant_notes = 'Test Order';
				}
				if(is_object($paymentInfo->buyItNow)){
					$paymentInfo->buyItNow->merchant_notes = 'Test Order';
				}
				$buyAuction = new PaymentBuyAuction($paymentInfo);
				$buyAuction->setProcessInfo(array('paymentType' => 3));
				$buyAuction->save()->redirect();
			}
			if(is_object($paymentInfo->bidPack)){
				$buyBid = new PaymentBuyBid($paymentInfo);
				$buyBid->setProcessInfo(array('paymentType' => 3));
				$buyBid->save()->redirect();
			}
		}

	}

    public function actionZeroPayment(){
        $paymentCode = Parameters::get()->paymentCode;
        if(empty($paymentCode)) $this->redirect(Yii::app()->createUrl('.'));
        $paymentInfo = new PaymentInfo();
        $paymentInfo->setPaymentCode($paymentCode)->getCache();

        if(is_object($paymentInfo->orderInfo)){
            $orderInfo = $paymentInfo->orderInfo;
        }
        if(is_object($paymentInfo->buyItNow)){
            $paymentInfo->buyItNow->setAuctionInfo($paymentInfo->auction);
            $orderInfo = $paymentInfo->buyItNow;
        }
        $auctionsInfo = $paymentInfo->auction;
        if($orderInfo->type==2){    //buy it now
            $totalpay = $orderInfo->attributes['total_price'];
        }else{
//             $price = $auctionsInfo->current_price >$auctionsInfo->value_price ? 0 : $auctionsInfo->current_price;
//             $totalpay = $price + $auctionsInfo->cost;
            $totalpay= $paymentInfo->totalprice;
        }
        $paymentInfo->totalPrice = $totalpay;
        if(!$paymentInfo->vaild()){
            $orderError = new OrderErrorLog();
            $orderError->customer_id 	= $paymentInfo->customer->id;;
            $orderError->auction_id 	= $paymentInfo->auction->id;
            $orderError->created 		= time();
            $orderError->post_data 		= json_encode($paymentInfo->toArray());
            $orderError->error_message  = json_encode($paymentInfo->errorMessage());
            $orderError->url			= Yii::app()->request->getUrl();
            $orderError->save(false);
            $this->redirect(Yii::app()->createUrl('.'));
        }

        //do zero payment
        $api = new ZeroPayment($paymentInfo);

        $api->apiRequest();

        //$response = $api->apiResponse();
        if($api->apiPaymentVaild()){
            if(is_object($paymentInfo->orderInfo)||is_object($paymentInfo->buyItNow)){
                if(is_object($paymentInfo->orderInfo)){
                    $paymentInfo->orderInfo->merchant_notes = 'Zero Order';
                }
                if(is_object($paymentInfo->buyItNow)){
                    $paymentInfo->buyItNow->merchant_notes = 'Zero Order';
                }
                
                $buyAuction = new PaymentBuyAuction($paymentInfo);
                
                $buyAuction->setProcessInfo(array('paymentType' => 3));
                $buyAuction->save()->redirect();
            }
            if(is_object($paymentInfo->bidPack)){
                $buyBid = new PaymentBuyBid($paymentInfo);
                $buyBid->setProcessInfo(array('paymentType' => 3));
                $buyBid->save()->redirect();
            }
        }else{
            
            $this->redirect(Yii::app()->createUrl('.'));
        }
    }
	
	public function actionBraintree(){
		$paymentCode = Parameters::get()->paymentCode;
		$paymentInfo = new PaymentInfo();
		$paymentInfo->setPaymentCode($paymentCode)->getCache();
		if(!$paymentInfo->vaild()){

			$orderError = new OrderErrorLog();
			$orderError->customer_id 	= $paymentInfo->customer->id;;
			$orderError->auction_id 	= $paymentInfo->auction->id;
			$orderError->created 		= time();
			$orderError->post_data 		= json_encode($paymentInfo->toArray());
			$orderError->error_message  = json_encode($paymentInfo->errorMessage());
			$orderError->url			= Yii::app()->request->getUrl();
			$orderError->save(false);
			$this->redirect(Yii::app()->createUrl('.'));
		}
		
		$api = new Braintree($paymentInfo);
		$response=$api->apiRequest();
		$response_json=json_encode($api->apiResponse());
		if ($api->apiPaymentVaild()){
			
			if(is_object($paymentInfo->bidPack)){
				$buyBid = new PaymentBuyBid($paymentInfo);
				$buyBid->setProcessInfo(array('paymentType' => 2));				
				$buyBid->save();
				
			}
			if(is_object($paymentInfo->orderInfo)||is_object($paymentInfo->buyItNow)){
				$buyAuction = new PaymentBuyAuction($paymentInfo);				
				$buyAuction->setProcessInfo(array('paymentType' => 2));
				$buyAuction->response=$response_json;
				$buyAuction->save()->redirect();
			}
		}else{
			Yii::app()->session['paymentError'] = array(
				'paymentCode'	=>	$paymentCode,
				'paymentType'	=>	Braintree::API_NAME,
			);
			//$couponCodeValidService = new CouponCodeVerificationService();
			//$couponCodeValidService->setCouponCode($paymentInfo->coupon_code)->addCouponCode();
		
			$response=$api->paymentLog(json_encode($response));
			$model = new PaymentLog();
			$model->type = 2;
			$model->request = $paymentCode;
			$model->customer_id = Yii::app()->user->id;
			$model->created = time();
			$model->response = json_encode(json_encode($response));
			$model->save();
				
			Yii::app()->session['payment_error'] = 'Please try using PayPal or call your Bank/Credit Card Company and ask them to approve transactions to eGunner Penny Auctions, LLC. If you have further questions, please contact eGunner Penny Auctions support at: https://egunner.desk.com!';
			$this->redirect(Yii::app()->baseUrl.'/myaccount/bidcredithistory');			
		}
		$this->redirect(Yii::app()->baseUrl.'/myaccount/bidcredithistory');
	}
}